#include <iostream>
#include <string>
#include <unistd.h>
#include <vector>
#include <sys/types.h>

using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::cerr;

void CreateChannelAndSub(int num, vector<Channel>* channels)
{
    int Allnum = num;
    while(num--)
    {
        // 1.创建管道
        int pipefd[2] = { 0 };
        int n = pipe(pipefd);

        if(n < 0) exit(1);

        // 2.创建子进程
        pid_t id = fork();

        if(id == 0)
        {
            // child read
            close(pipefd[1]);
            work(pipefd[0]);
            close(pipefd[0]);
            exit(0);
        }

        int channel_num = Allnum - num;
        string channel_name = std::to_string(channel_num);

        // 父进程
        close(pipefd[0]);

        channels->push_back(Channel(pipefd[1], id, channel_name));

    }
}

void work(int wfd)
{
    while(true) sleep(1);
}

class Channel
{
public:
    Channel(int wfd, pid_t id, const string& name)
        :_wfd(wfd), _subprocessid(id), _name(name)
    {}
    int GetWfd(){ return _wfd; }
    pid_t GetProcessID(){ return _subprocessid; }
    string GetName(){ return _name; }
    ~Channel(){}
private: 
    int _wfd;
    pid_t _subprocessid;
    string _name;
};


int main(int argc, char* argv[])
{
    if(argc != 2)
        cerr << "Correct Usage:" << argv[0] << " processnum" << endl;

    int num = std::stoi(argv[1]);


    vector<Channel> channels;

    // 1. 创建信道和子进程
    CreateChannelAndSub(num, &channels);

    // 2. 通过channel控制子进程
    


    // for(auto& channel : channels)
    // {
    //     cout << "==========================================" << endl;
    //     cout << channel.GetName() << endl;
    //     cout << channel.GetWfd() << endl;
    //     cout << channel.GetProcessID() << endl;
    // }

    return 0;
}